package cn.git.bbs.core.service.solr;


import cn.git.bbs.core.bean.product.Product;
import cn.git.bbs.core.bean.product.ProductQuery;
import cn.git.bbs.core.bean.product.Sku;
import cn.git.bbs.core.bean.product.SkuQuery;
import cn.git.bbs.core.dao.product.ProductMapper;
import cn.git.bbs.core.dao.product.SkuMapper;
import cn.itcast.common.page.Pagination;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;



@Service("searchService")
public class SearchServiceImpl implements SearchService {

    @Autowired
    private SolrServer solrServer;

    public Pagination selectPaginationByQuery(String keyword, Integer pageNo,Long brandId,String price) throws Exception {
        //拼接条件
        StringBuffer str = new StringBuffer();
        str.append("keyword=").append(keyword);

        ProductQuery productQuery = new ProductQuery();
        productQuery.setPageSize(15);
        productQuery.setPageNo(Pagination.cpn(pageNo));

        //过滤条件
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.set("q","name_ik:"+keyword);
        if (null!=brandId){
            solrQuery.addFilterQuery("brandId:" +brandId);
        }
        if(null!=price){
            String[] split = price.split("-");
            if(split.length == 2){
                solrQuery.addFilterQuery("price:["+split[0]+" TO "+split[1]+"]");
            }else {
                solrQuery.addFilterQuery("price:["+split[0]+" TO *]");
            }
        }

        //高亮
        solrQuery.setHighlight(true);
        solrQuery.addHighlightField("name_ik");
        solrQuery.setHighlightSimplePre("<span style='color:red'>");
        solrQuery.setHighlightSimplePost("</span>");

        //排序
        solrQuery.setSort("price", SolrQuery.ORDER.asc);

        //分页
        solrQuery.setStart(productQuery.getStartRow());
        solrQuery.setRows(productQuery.getPageSize());

        //执行查询
        QueryResponse query = solrServer.query(solrQuery);

        //查询结果集
        SolrDocumentList results = query.getResults();

        //查询总条数
        long numFound = results.getNumFound();

        //取高亮
        Map<String, Map<String, List<String>>> highlighting = query.getHighlighting();
        List<Product> products = new ArrayList<Product>();
        for (SolrDocument doc:results) {
            Product product = new Product();

            //设置id
            String id =(String)doc.get("id");
            product.setId(Long.parseLong(id));
            Map<String, List<String>> stringListMap = highlighting.get(id);
            List<String> name_ik = stringListMap.get("name_ik");
            product.setName(name_ik.get(0));
            String url = (String) doc.get("url");
            product.setImgUrl(url);

            //设置价格

            product.setPrice((Float) doc.get("price"));

            //设置平台id
            Object brandId1 = doc.get("brandId");
            product.setBrandId(Long.parseLong(brandId1.toString()));
            products.add(product);
        }
        //创建分页对象
        Pagination pagination = new Pagination(
                productQuery.getPageNo(),
                productQuery.getPageSize(),
                (int) numFound,
                products
        );

        String url = "/search";
        pagination.pageView(url,str.toString());
        return pagination;
    }
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private SkuMapper skuMapper;
    public void insertProductIntoSolr(Long id){
        SolrInputDocument document = new SolrInputDocument();
        Product p = productMapper.selectByPrimaryKey(id);
        document.setField("id",id);
        document.setField("name_ik",p.getName());
        document.setField("url",p.getImages()[0]);
        document.setField("brandId",p.getBrandId());
        //查询价格   select price form bbs_sku where product_id = 442 order by price asc limit 0,1
        SkuQuery skuQuery = new SkuQuery();
        skuQuery.setPageNo(1);
        skuQuery.setPageSize(1);
        skuQuery.createCriteria().andProductIdEqualTo(id);
        skuQuery.setOrderByClause("price");
        List<Sku> skus = skuMapper.selectByExample(skuQuery);
        document.setField("price",skus.get(0).getPrice());
        try {
            solrServer.add(document);
            solrServer.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
